package com.yao.ui.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v4.app.FragmentManager
import android.util.Log
import android.view.View
import com.base.fragment.BaseDialogFragment
import com.lib.updater.Updater
import com.lib.updater.UpdaterConfig
import com.yao.R
import com.yao.helper.DialogFragmentHelper
import kotlinx.android.synthetic.main.fragment_update.*

class UpdateDialogFragment : BaseDialogFragment() {

    companion object {
        private const val VERSION = "version"
        private const val CONTENT = "content"
        private const val URL = "url"
        private const val TAG = "update"

        fun show(fragmentManager: FragmentManager, str: String, content: String, url: String) {
            val fragment = UpdateDialogFragment()
            val bundle = Bundle()
            bundle.putString(VERSION, str)
            bundle.putString(CONTENT, content)
            bundle.putString(URL, url)
            fragment.arguments = bundle
            DialogFragmentHelper.showDialogFragment(fragmentManager, fragment, TAG)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_update
    }

    override fun initView(p0: Bundle?) {
        var version = arguments?.getString(VERSION)
        var content = arguments?.getString(CONTENT)
        var url = arguments?.getString(URL)

        version?.let {
            tv_version?.text = "V.$it"
        }

        content?.let {
            tv_desc?.text = it
        }

        bt_update.setOnClickListener {
            val builder = UpdaterConfig.Builder()
            builder.setTitle(resources.getString(R.string.app_name))
            builder.setDescription(content)
            builder.setDownloadUrl(url)
            builder.setIsShowDownloadUI(true)
            builder.setIsLog(true)
            Updater.update(context, builder.build()) { process, max ->
                bt_update.visibility = View.INVISIBLE
                bt_update.isClickable = false
                pb_update.visibility = View.VISIBLE
                pb_update.progress = (process * 100F / max).toInt()
                tv_pb.visibility = View.VISIBLE
                tv_pb.text = "${(process * 100F / max).toInt()} / 100"
                Log.d("ttt", "$process---$max")
                if (process == max) {
                    dismiss()
                }
            }
        }
    }

    override fun release() {
        Updater.release(context)
    }
}